<template>
  <el-container style="height: 100vh; border: 1px solid #eee; overflow: hidden">
    <el-main>
      <div class="user">
        <div class="hm-search">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品列表</el-breadcrumb-item>
          </el-breadcrumb>
          <div class="m-search">
            <el-input v-model="params.query" @keyup.enter="getUsersBySearch">
              <template #append>
                <el-button icon="el-icon-search" @click="getUsersBySearch"></el-button>
              </template>
            </el-input>
          </div>
          <div class="m-primary">
            <el-button type="primary" @click="userInfoDialog=true">添加用户</el-button>
          </div>
        </div>
        <div class="users-tab">
          <el-table :data="usersData.users"  border style="width: 100%">
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="username" label="姓名"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="mobile" label="电话"></el-table-column>
            <el-table-column prop="create_time" label="创建日期" :formatter="dateFormat"></el-table-column>
            <el-table-column prop="mg_state" label="用户状态">
              <template #default="scope">
                <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="changeUserStatusFn($event,scope.row)"/>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary" icon="el-icon-edit" circle @click="editDialogFn(scope.row)"></el-button>
                <el-button type="danger" icon="el-icon-delete" circle @click="deleteUserFn(scope.row.id)"></el-button>
                <el-button type="success" icon="el-icon-check" circle @click="deliverDialogFn(scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 点击添加用户弹出的对话框 -->
          <el-dialog title="添加用户" v-model="userInfoDialog">
            <el-form :model="userInfoForm" ref="userForm">
              <el-form-item label="用户名" :label-width="formLabelWidth"
                prop="username"
                :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]"
              >
                <el-input v-model="userInfoForm.username" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="密码" :label-width="formLabelWidth"
                prop="password"
                :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
              >
                <el-input v-model="userInfoForm.password" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="电话" :label-width="formLabelWidth">
                <el-input v-model="userInfoForm.mobile" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" :label-width="formLabelWidth"
                prop="email"
                :rules="[
                { required: true, message: '请输入密码', trigger: 'blur' },
                { type:'email', message:'请输入正确邮箱', trigger: ['blur','change'] }
                ]"
              >
                <el-input v-model="userInfoForm.email" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="userInfoDialog = false">取消</el-button>
                <el-button type="primary"  @click="addUsersFn()">确定</el-button>
              </span>
            </template>
          </el-dialog>

          <!-- 点击编辑用户 -->
          <el-dialog title="编辑用户" v-model="editUserInfoDialog">
            <el-form :model="editUserInfoForm" ref="editUserForm">
              <el-form-item label="用户名" :label-width="formLabelWidth"
                prop="username"
                :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]"
              >
                <el-input v-model="editUserInfoForm.username" autocomplete="off" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="电话" :label-width="formLabelWidth">
                <el-input v-model="editUserInfoForm.mobile" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" :label-width="formLabelWidth"
                prop="email"
                :rules="[
                { required: true, message: '请输入密码', trigger: 'blur' },
                { type:'email', message:'请输入正确邮箱', trigger: ['blur','change'] }
                ]"
              >
                <el-input v-model="editUserInfoForm.email" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="editUserInfoDialog = false">取消</el-button>
                <el-button type="primary"  @click="editUsersFn()">确定</el-button>
              </span>
            </template>
          </el-dialog>

          <!-- 分配角色 -->
          <el-dialog title="分配角色" v-model="deliverRoleDialog">
            <el-form :model="deliverRoleForm" ref="delRoleForm">
              <el-form-item label="用户名" :label-width="formLabelWidth"
                prop="username"
                :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]"
              >
                <el-input v-model="deliverRoleForm.username" autocomplete="off" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="角色" :label-width="formLabelWidth">
                <el-select v-model="deliverRoleForm.rid" placeholder="请选择">
                  <el-option label="请选择"  :disabled="true" :value="-1"></el-option>
                  <el-option
                    v-for="item in roleObj.roleList"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="deliverRoleDialog = false">取消</el-button>
                <el-button type="primary" @click="deliverRolesFn()">确定</el-button>
              </span>
            </template>
          </el-dialog>

          <!-- 分页 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            v-model:currentPage="params.pagenum"
            :page-sizes="[1, 3, 5, 10]"
            :page-size="params.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="usersData.total"
          >
          </el-pagination>
         
        </div>
      </div>
    </el-main>
  </el-container>
</template>
<script>
import { reactive, onMounted,getCurrentInstance, ref } from "vue";
import { useRouter } from "vue-router";
import { getUsers,changeUserStatus,addUsers,exidUsers,delectUser,getRoles,getRid,assignRoles } from "../../http/api"
import moment from "moment";
import { ElMessageBox, ElMessage } from "element-plus";
export default{
  setup(){
    const {proxy}=getCurrentInstance()
    const router = useRouter();
    let usersData = reactive({});
    let params = reactive({
      pagenum: router.pagenum || 1,
      pagesize: router.pagesize ||10,
      query: router.query || "",
    });
    let formLabelWidth = "120px";
    // 添加用户状态
    let userInfoDialog = ref(false);
    let userInfoForm = reactive({
      username:'',
      password:'',
      email:'',
      mobile:''
    });
    // 点击编辑用户的状态
    let editUserInfoDialog = ref(false);
    let editUserInfoForm = reactive({
      username:'',
      id:'',
      email:'',
      mobile:''
    });

    let roleObj = reactive({
      roleList:[]


    });
    // 分配角色的状态
    let deliverRoleDialog = ref(false);
    let deliverRoleForm = reactive({
      id:'',
      rid:'',
      username:''
    });

    //获取用户列表
    const getUsersFn = async () => {
      const res = await getUsers(params);
      Object.assign(usersData, res);
    };

    //搜索商品
    const getUsersBySearch=()=>{
      router.push({
        query:Object.assign({},router.query,{
          query:params.query
        })
         })
      getUsersFn();
    }
    
    // 添加用户
    const userForm=ref();
    const addUsersFn = ()=>{
      proxy.$refs.userForm.validate(async valid=>{
        if(valid){
          await addUsers(userInfoForm);
          userInfoDialog.value=false;
          // 重置
          proxy.$refs.userForm.resetFields();
          getUsersFn();
        }
      })
    }

    
    // 修改用户状态的方法
    const changeUserStatusFn = async(val,user) =>{
      await changeUserStatus(user.id,val);
      getUsersFn();
    };
    
    // 编辑用户的消息弹框  回显信息
    const editUserForm=ref();
    const editDialogFn = (obj)=>{
      const {id,username,email,mobile}=obj;
      editUserInfoForm.id=id;
      editUserInfoForm.username=username;
      editUserInfoForm.email=email;
      editUserInfoForm.mobile=mobile;
      editUserInfoDialog.value=true;

    };

    // 编辑用户提交
    const editUsersFn = async ()=>{
      await exidUsers(editUserInfoForm.id,editUserInfoForm);
      editUserInfoDialog.value=false;
      getUsersFn();
    };

    // 删除用户
    const deleteUserFn = (id)=>{
      ElMessageBox.confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "OK",
          cancelButtonText: "Cancel",
          type: "warning",
        }
      ).then(async() => {
          await delectUser(id);
        getUsersFn()
        
      }).catch(() => {
        ElMessage({
          type: "info",
          message: "已取消删除",
        });
      });

    };

    // 分配角色的消息弹框
    const delRoleForm = ref();
    const deliverDialogFn = async(obj) =>{
      console.log('obj---',obj);
      const {id,username}=obj;
      deliverRoleDialog.value=true;

      // 获取角色列表
      const res=await getRoles();
      console.log('12421',res);
      roleObj.roleList=res;

      // 获取角色id
      const {rid}=await getRid(id);
      deliverRoleForm.id=id;
      deliverRoleForm.username=username;
      deliverRoleForm.rid=rid;
    };

    // 分配角色
    const deliverRolesFn = async ()=>{
      const {id,rid}=deliverRoleForm;
      await assignRoles(id,rid)
      deliverRoleDialog.value=false;

      getUsersFn();
    };




    //日期转化
    const dateFormat=(row, column) =>{
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    };
    //每页的条数
    const handleSizeChange=(val)=>{
      params.pagesize=val
      router.push({
        query:Object.assign({},router.query,{
          query:params.query
        })
        
      })
      getUsersFn();
    };
    //当前是第几页
    const  handleCurrentChange=(val)=>{
      params.pagenum=val
      router.push({
        query:Object.assign({},router.query,{
          query:params.query
        })
         })
      getUsersFn();
    }




    onMounted(() => {
      getUsersFn();
    });
    return{
      usersData,
      params,
      proxy,
      getUsersFn,
      dateFormat,
      getUsersBySearch,
      changeUserStatusFn,
      formLabelWidth,
      userInfoDialog,
      userInfoForm,
      userForm,
      addUsersFn,
      editUserForm,
      editDialogFn,
      editUserInfoDialog,
      editUserInfoForm,
      editUsersFn,
      deleteUserFn,
      delectUser,
      deliverRoleDialog,
      deliverRoleForm,
      roleObj,
      deliverDialogFn,
      deliverRolesFn,
      delRoleForm,
      handleSizeChange,
      handleCurrentChange
    }

  }
}

</script>
<style scoped lang="scss">
.m-search {
  float: left;
  width: 250px;
  margin-top: 15px;
}
.m-primary {
  float: left;
  margin-left: 20px;
  margin-top: 15px;
  margin-bottom: 15px;
}
a {
  text-decoration: none;
  color: #333;
}
.hm-search {
  height: 70px;
}
.el-main {
  background-color: #eee;
}
.user {
  background-color: #fff;
  padding: 15px;
}
</style>